package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";
    public static String YYYYMM = "yyyyMM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 和当前时间相减 秒数
     *
     * @return Date() 当前日期
     */
    public static Long getDatediffOfSeconds(String date1)
    {
        Date start = parseDate(date1); // 开始时间
        // 执行一些操作
        Date end = new Date(); // 结束时间

        return (end.getTime() - start.getTime())/1000; // 时间差（毫秒）

    }
    //计算年龄
    public static int getAgeBybirthday(String date)
    {
        String[] birthdayArray = date.split("-");
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        return currentYear - Integer.parseInt(birthdayArray[0]);
    }
    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }
    /**
     * 获取上第几个月的月份
     *
     * @param n
     * @return
     */
    public static String getLastNMonth(int n) {
        Calendar cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, -n);
        return parseDateToStr(YYYYMM,cale.getTime());
    }
    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }
    /**
     * @param time   毫秒
     * @param format 格式
     * @return Date类型
     */
    public static Date timeToDate(long time, String format) {
        try {
            Date date = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            String formattedDateTime = sdf.format(date);
            DateFormat formatter = new SimpleDateFormat(format);
            return dateTime(format,formattedDateTime);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * @param @param  date
     * @param @param  n
     * @param @return 设定文件
     * @return Date    返回类型
     * @throws
     * @Title: addDay
     * @Description: (增加日期)
     */
    public static Date addDay(Date date, int n) {
        try {
            Calendar cd = Calendar.getInstance();
            cd.setTime(date);
            cd.add(Calendar.DATE, n);
            return cd.getTime();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }
    /**
     * 获取当天
     */
    public static int getCurrentDay(){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }
    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
    /**
     * 判断是否在指定时间内
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean IsTimeIn(String beginTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        try {
            Date date = new Date();
            Date dateTime = sdf.parse(sdf.format(date));
            Date beginDate = sdf.parse(beginTime);
            Date endDate = sdf.parse(endTime);
            return dateTime.getTime() >= beginDate.getTime() && dateTime.getTime() <= endDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }
    public static Date addHour(Date date, int n) {
        try {
            Calendar cd = Calendar.getInstance();
            cd.setTime(date);
            cd.add(Calendar.HOUR_OF_DAY, n);
            return cd.getTime();
        } catch (Exception e) {
            return null;
        }
    }
    //判断时间是否大于本周
    public static boolean isThisWeek(String time) {
        Calendar calendar = Calendar.getInstance();
        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        calendar.setTime(parseDate(time));
        int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        return paramWeek > currentWeek;
    }
    /**
     * 判断日期是否周末
     *
     * @param date
     * @return
     */
    public static boolean isWeekend(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断日期是否周五
     *
     * @param date
     * @return
     */
    public static boolean isFriday(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断日期是本周第几天
     *
     * @param date
     * @return
     */
    public static int getDayOfWeek(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            return cal.get(Calendar.DAY_OF_WEEK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 判断日期是否周六
     *
     * @param date
     * @return
     */
    public static boolean isSaturday(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断日期是否周日
     *
     * @param date
     * @return
     */
    public static boolean isSunday(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断日期是否周二到周六
     *
     * @param date
     * @return
     */
    public static boolean isBetweenWeek2And6(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) >= 3 && cal.get(Calendar.DAY_OF_WEEK) <= 7) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据时间计算出上周日和这周六
     * @param date
     * @return
     */
    public static List<String> getSundayAndSaturday(Date date) {
        List<String> list = new ArrayList<String>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeekMonday = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeekMonday != Calendar.MONDAY) {
            // 若不是星期一，则将日期调整到本周的第一天（星期一）
            calendar.add(Calendar.DATE, -1 * (dayOfWeekMonday - Calendar.MONDAY));
        }
        calendar.add(Calendar.DATE, -1); // 减去1天得到周日
        list.add(parseDateToStr(YYYY_MM_DD,calendar.getTime()) );

        calendar.add(Calendar.DATE, 7); // 再加上7天得到周六
        list.add(parseDateToStr(YYYY_MM_DD,calendar.getTime()) );

        return list;
    }
}
